<template>
  <div class="region-selector">
    <!-- 省份选择 -->
    <select v-model="selectedProvince" class="region-select">
      <option value="">请选择省份</option>
      <option v-for="province in provinces" :key="province.code" :value="province.name">
        {{ province.name }}
      </option>
    </select>

    <!-- 城市选择 - 直辖市时隐藏 -->
    <select 
      v-if="!isMunicipality"
      v-model="selectedCity" 
      class="region-select"
      :disabled="!selectedProvince"
    >
      <option value="">请选择城市</option>
      <option v-for="city in cities" :key="city.code" :value="city.name">
        {{ city.name }}
      </option>
    </select>

    <!-- 区县选择 -->
    <select 
      v-model="selectedDistrict" 
      class="region-select"
      :disabled="!selectedProvince || (!isMunicipality && !selectedCity)"
    >
      <option value="">请选择区县</option>
      <option v-for="district in districts" :key="district.code" :value="district.name">
        {{ district.name }}
      </option>
    </select>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { 
  getProvinces, 
  getPrefectures, 
  getCounties, 
  getCodeByProvinceName,
} from 'china-region';
import type{Region}from 'china-region';

// 定义Props接口
interface RegionProps {
  province?: string;
  city?: string;
  district?: string;
}

const props = withDefaults(defineProps<RegionProps>(), {
  province: '',
  city: '',
  district: ''
});

// 定义Emits
const emit = defineEmits<{
  (e: 'update:province', value: string): void;
  (e: 'update:city', value: string): void;
  (e: 'update:district', value: string): void;
  (e: 'change', value: RegionOutput): void;
}>();

// 定义输出类型
interface RegionOutput {
  province: string;
  city: string;
  district: string;
  fullCode?: string;
}

// 直辖市列表
const municipalities = ['北京市', '天津市', '上海市', '重庆市'];

// 响应式数据
const provinces = ref<Region[]>(getProvinces());
const cities = ref<Region[]>([]);
const districts = ref<Region[]>([]);

const selectedProvince = ref(props.province || '');
const selectedCity = ref(props.city || '');
const selectedDistrict = ref(props.district || '');

// 计算是否为直辖市
const isMunicipality = computed(() => {
  return municipalities.includes(selectedProvince.value);
});

// 监听省份变化
watch(selectedProvince, (newProvince) => {
  // 重置下级选择
  selectedCity.value = '';
  selectedDistrict.value = '';
  cities.value = [];
  districts.value = [];
  
  if (newProvince) {
    // 获取省份代码
    const provinceCode = getCodeByProvinceName(newProvince);
    
    if (isMunicipality.value) {
      // 如果是直辖市，直接加载区县数据
      districts.value = getCounties(provinceCode);
      
      // 如果props中有默认区县值，尝试选中
      if (props.district) {
        const targetDistrict = districts.value.find(district => district.name === props.district);
        if (targetDistrict) selectedDistrict.value = props.district;
      }
    } else {
      // 非直辖市，加载城市数据
      cities.value = getPrefectures(provinceCode);
      
      // 如果props中有默认城市值，尝试选中
      if (props.city) {
        const targetCity = cities.value.find(city => city.name === props.city);
        if (targetCity) selectedCity.value = props.city;
      }
    }
  }
  
  emit('update:province', newProvince);
  // 如果是直辖市，城市值设为与省份相同
  emit('update:city', isMunicipality.value ? newProvince : '');
  emitChangeEvent();
});

// 监听城市变化
watch(selectedCity, (newCity) => {
  selectedDistrict.value = '';
  districts.value = [];
  
  if (newCity && !isMunicipality.value) {
    // 查找城市代码并加载区县数据
    const cityCode = cities.value.find(item => item.name === newCity)?.code;
    if (cityCode) {
      districts.value = getCounties(cityCode);
    }
    
    // 如果props中有默认区县值，尝试选中
    if (props.district) {
      const targetDistrict = districts.value.find(district => district.name === props.district);
      if (targetDistrict) selectedDistrict.value = props.district;
    }
  }
  
  emit('update:city', isMunicipality.value ? selectedProvince.value : newCity);
  emitChangeEvent();
});

// 监听区县变化
watch(selectedDistrict, (newDistrict) => {
  emit('update:district', newDistrict);
  emitChangeEvent();
});

// 监听props变化，更新选中值
watch(() => props.province, (newVal) => {
  if (newVal) selectedProvince.value = newVal;
});

watch(() => props.city, (newVal) => {
  if (newVal && cities.value.some(city => city.name === newVal)) {
    selectedCity.value = newVal;
  }
});

watch(() => props.district, (newVal) => {
  if (newVal && districts.value.some(district => district.name === newVal)) {
    selectedDistrict.value = newVal;
  }
});

// 发出变化事件
function emitChangeEvent() {
  const output: RegionOutput = {
    province: selectedProvince.value,
    city: isMunicipality.value ? selectedProvince.value : selectedCity.value,
    district: selectedDistrict.value
  };
  
  emit('change', output);
}

// 计算完整地区信息
const fullRegion = computed(() => {
  return `中国,${selectedProvince.value},${isMunicipality.value ? '' : selectedCity.value},${selectedDistrict.value}`;
});

// 暴露方法和数据给父组件
defineExpose({
  selectedProvince,
  selectedCity,
  selectedDistrict,
  fullRegion,
  isMunicipality,
  clearAll: () => {
    selectedProvince.value = '';
    selectedCity.value = '';
    selectedDistrict.value = '';
  }
});
</script>

<style scoped>
.region-selector {
  display: flex;
  gap: 12px;
}

.region-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 120px;
}

.region-select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
